<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 巡检任务 </span>
      </template>
      <template #toolbar>
        <!-- <a-button type="primary" @click="handleForm({})" v-auth="'inspectionmanag:inTaskCollection:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button> -->
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ tid: record.tid })">
          {{ record.taskId }}
        </a>
      </template>
      <!-- 新增 action 插槽 -->
      <template #action="{ record }">
        <a-button 
        @click="handleForm({ id: record.id })" 
        v-auth="'inspectionmanag:inTaskCollection:edit'" 
        type="text"
        >
          <span style="font-size: 14px; color: #7B68EE; margin-right: 5px;">巡检视频</span>
        </a-button>
        <a-button 
        @click="handleFormDetail({ id: record.id })" 
        type="text"
        >
          <span style="font-size: 14px; color: #4169E1;">详情</span>
        </a-button>
        <!-- <a-button
          @click="handleDownload(record)"
          v-auth="'inspectionmanag:inTaskCollection:edit'"
          type="danger"
        >
          {{ t('下载') }}
        </a-button> -->
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormDetail @register="registerDrawerDetail" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup name="ViewsInspectionmanagInTaskCollectionList">
import { unref, ref, onMounted } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { inTaskCollectionDelete, inTaskCollectionListData } from '/@/api/inspectionmanag/inTaskCollection';
import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
import { useDrawer } from '/@/components/Drawer';
import { FormProps } from '/@/components/Form';
import InputForm from './form.vue';
import FormDetail from './formDetail.vue';
import { officeTreeData } from '/@/api/sys/office';
import { useDataFetching } from '/@/utils/Deduplicate';

// 使用组合式函数
const { uniqueArray, getAllData } = useDataFetching(); 
const { t } = useI18n('inspectionmanag.inTaskCollection');
const { showMessage } = useMessage();
const { meta } = unref(router.currentRoute);

const getTitle = {
  icon: meta.icon || 'i-ant-design:book-outlined',
  value: meta.title || t('任务领取表管理'),
};
const EnterpriseParams = ref<Recordable>({
  name: ''
});

const searchForm: FormProps = {
  baseColProps: { md: 8, lg: 6 },
  labelWtidth: 90,
  schemas: [
    {
      label: t(''),
      field: 'taskTypeName',
      fieldLabel: 'taskTypeCode',
      component: 'Select',
      componentProps: {
        placeholder: t('请输入任务类型名称'),
        dictType: 'task_type',
        resultFieldNames: { label: 'dictLabel', value: 'dictValue' },
      }
    },
    {
      label: t(''),
      field: 'taskStatus',
      component: 'Select',
      componentProps: {
        placeholder: t('任务状态'),
        options: [
          { label: t('已完成'), value: '已完成' },
          { label: t('未完成'), value: '未完成' },
          { label: t('进行中'), value: '进行中' }
        ]
      }
    },
    {
      label: t(''),
      field: 'enterpriseCode',
      fieldLabel: 'enterpriseName',
      component: 'TreeSelect',
      componentProps: () => {
        return {
          placeholder: t('输入主体名称'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
        };
      },
    },
    {
      label: t(''),
      field: 'receiveTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        placeholder: t('请选择领取时间'),
      },
    },
    {
      label: t(''),
      field: 'finishTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        placeholder: t('请选择完成时间'),
      },
    },
  ],
};

const tableColumns: BasicColumn[] = [
  {
    title: t('任务名称'),
    dataIndex: 'taskName',
    key: 'a.task_name',
    sorter: false,
    width: 130,
    align: 'left',
  },
  {
    title: t('任务类型名称'),
    dataIndex: 'taskTypeName',
    key: 'a.task_type_name',
    sorter: false,
    width: 130,
    align: 'left',
  },
  {
    title: t('任务状态'),
    dataIndex: 'taskStatus',
    key: 'a.task_status',
    sorter: false,
    width: 130,
    align: 'left',
  },
  {
    title: t('所属企业'),
    dataIndex: 'enterpriseName',
    key: 'a.enterprise_name',
    sorter: false,
    width: 130,
    align: 'left',
  },
  {
    title: t('角色名称'),
    dataIndex: 'roleName',
    key: 'a.role_name',
    sorter: false,
    width: 130,
    align: 'left',
  },
  {
    title: t('领取时间'),
    dataIndex: 'receiveTime',
    key: 'a.receive_time',
    // sorter: false,
    width: 130,
    align: 'center',
    defaultSortOrder: 'descend', // 默认上到下为由大到小的顺序
    sorter: (a, b) => { return a.receiveTime> b.receiveTime? 1 : -1 },
  },
  {
    title: t('完成时间'),
    dataIndex: 'finishTime',
    key: 'a.finish_time',
    // sorter: false,
    width: 130,
    align: 'center',
    defaultSortOrder: 'descend', // 默认上到下为由大到小的顺序
    sorter: (a, b) => { return a.finishTime> b.finishTime? 1 : -1 },
  },
  {
    title: t('操作'),
    dataIndex: 'action',
    key: 'action',
    width: 160,
    fixed: 'right',
    slots: { customRender: 'action' }, // 使用自定义插槽
  },
];

let IdFromUrl = '';
const [registerTable, { reload }] = useTable({
  api: inTaskCollectionListData,
  beforeFetch: (params) => {
    const urlParams = new URLSearchParams(router.currentRoute.value.fullPath.split('?')[1]);
      const Tid = urlParams.get('id');
      if (Tid) {
        IdFromUrl = decodeURIComponent(Tid);
        params.id = IdFromUrl;
      }
    params.taskStatus=params.taskStatus||'已完成';
    return params;
  },
  columns: tableColumns,
  actionColumn: null, // 不再使用默认的 actionColumn
  formConfig: searchForm,
  showTableSetting: true,
  useSearchForm: true,
  canResize: true,
});

const [registerDrawer, { openDrawer }] = useDrawer();
const [registerDrawerDetail, { openDrawer: openDrawerDetail }] = useDrawer();

function handleForm(record: Recordable) {
  console.log(record);
  openDrawer(true, record);
}

function handleFormDetail(record: Recordable) {
  console.log(record);
  openDrawerDetail(true, record);
}

// async function handleDelete(record: Recordable) {
//   const params = { tid: record.tid };
//   const res = await inTaskCollectionDelete(params);
//   showMessage(res.message);
//   handleSuccess(record);
// }

function handleSuccess(record: Recordable) {
  reload({ record });
}

onMounted(function getCurrentUrl() {
  const currentUrl = router.currentRoute.value.fullPath;
  console.log('当前页面的url地址是:', currentUrl);
  const urlParams = new URLSearchParams(currentUrl.split('?')[1]);
  const Id = urlParams.get('id');
  if (Id) {
    const decodedId = decodeURIComponent(Id);
    console.log('解码后的设备编码:', decodedId);
  }
  console.log('当前页面的url地址是:', currentUrl);
  return currentUrl;
});
</script>